<template>
  <div class="diet-records-wrapper">
    <div class="diet-records-container">
      <!-- 返回按钮 -->
      <button @click="goBack" class="back-button">返回</button>

      <h3>饮食记录</h3>
      <form @submit.prevent="submitDietRecord" class="diet-form">
        <div class="form-group">
          <label>食物名称:</label>
          <input
            type="text"
            v-model="dietRecord.foodItem"
            placeholder="请输入食物名称"
            required
          />
        </div>
        <div class="form-group">
          <label>卡路里:</label>
          <input
            type="number"
            v-model="dietRecord.calories"
            placeholder="请输入卡路里"
            required
          />
        </div>
        <div class="form-group">
          <label>份量:</label>
          <input
            type="text"
            v-model="dietRecord.servingSize"
            placeholder="请输入份量（如 1碗）"
            required
          />
        </div>
        <div class="form-group">
          <label>餐别:</label>
          <select v-model="dietRecord.mealType" required>
            <option value="Breakfast">早餐</option>
            <option value="Lunch">午餐</option>
            <option value="Dinner">晚餐</option>
            <option value="Snack">零食</option>
          </select>
        </div>
        <button type="submit" class="submit-button" :disabled="isSubmitting">
          {{ isSubmitting ? '提交中...' : '提交饮食记录' }}
        </button>
      </form>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'DietRecords',
  data() {
    return {
      dietRecord: {
        foodItem: '',
        calories: null,
        servingSize: '',
        mealType: '',
      },
      isSubmitting: false, // 加载状态
    };
  },
  methods: {
    goBack() {
      this.$router.go(-1); // 返回上一页
    },
    async submitDietRecord() {
      if (this.isSubmitting) return; // 防止重复提交
      this.isSubmitting = true; // 开始提交

      try {
        const token = localStorage.getItem('jwt'); // 从本地存储获取 JWT
        if (!token) {
          alert('请先登录');
          this.$router.push('/login'); // 跳转到登录页面
          return;
        }

        // 解析 JWT 获取 user_id
        const userId = this.getUserIdFromToken(token);
        if (!userId) {
          alert('无法获取用户 ID，请重新登录');
          this.$router.push('/login');
          return;
        }

        // 构造请求数据
        const dietRecord = {
          ...this.dietRecord,
          userId, // 添加 user_id
        };

        // 发送请求到后端
        const response = await axios.post(
          'http://127.0.0.1:8080/api/login/home/dietRecords',
          dietRecord,
          {
            headers: {
              Authorization: `Bearer ${token}`, // 添加 JWT 到请求头
            },
          }
        );

        // 处理后端响应
        if (response.data > 0) {
          alert('饮食记录提交成功！');
          this.resetForm(); // 重置表单
          this.$router.push('/home/diet-plans');
        } else {
          alert('饮食记录提交失败，请重试');
        }
      } catch (error) {
        console.error('提交饮食记录出错:', error);
        alert('提交饮食记录出错，请稍后重试');
      } finally {
        this.isSubmitting = false; // 提交结束
      }
    },
    // 解析 JWT 获取 user_id
    getUserIdFromToken(token) {
      try {
        // 分割 JWT 令牌，获取 Payload 部分
        const payloadBase64 = token.split('.')[1];
        // 将 URL 安全的 Base64 转换为标准 Base64
        const standardBase64 = payloadBase64.replace(/-/g, '+').replace(/_/g, '/');
        // 解码 Base64 字符串
        const payloadJson = atob(standardBase64);
        // 解析 JSON 对象
        const payload = JSON.parse(payloadJson);
        // 返回 userId
        return payload.userId;
      } catch (error) {
        console.error('解析 JWT 令牌出错:', error);
        return null;
      }
    },
    // 重置表单
    resetForm() {
      this.dietRecord = {
        foodItem: '',
        calories: null,
        servingSize: '',
        mealType: '',
      };
    },
  },
};
</script>

<style scoped>
body, html {
  height: 100%;
  margin: 0;
  font-family: Arial, sans-serif;
  background-color: #f0f2f5;
}

.diet-records-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh; /* 使容器占满整个视口高度 */
  background-image: url('/background2.jpg'); /* 添加背景图片 */
  background-size: cover; /* 背景图片覆盖整个容器 */
  background-position: center; /* 背景图片居中 */
  background-repeat: no-repeat; /* 背景图片不重复 */
}

.diet-records-container {
  max-width: 800px; /* 调整容器宽度 */
  width: 100%; /* 使容器占满父容器宽度 */
  margin: 0 auto;
  padding: 20px; /* 调整内边距 */
  text-align: center;
  background-color: rgba(255, 255, 255, 0.9); /* 白色背景，带透明度 */
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
}

.diet-form {
  display: flex;
  flex-direction: column;
  gap: 16px; /* 调整表单元素之间的间距 */
}

.form-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  width: 100%; /* 使表单组占满容器宽度 */
}

label {
  font-size: 16px; /* 调整标签字体大小 */
  color: #555;
  margin-bottom: 8px; /* 调整标签与输入框的间距 */
}

input,
select {
  width: 100%; /* 输入框占满容器宽度 */
  padding: 12px; /* 调整输入框内边距 */
  border: 1px solid #ddd;
  border-radius: 6px; /* 调整输入框圆角 */
  font-size: 16px; /* 调整输入框字体大小 */
  box-sizing: border-box; /* 确保内边距和边框不增加输入框的总宽度 */
}

select {
  appearance: none; /* 移除默认下拉箭头 */
  background-color: white;
}

.submit-button {
  background-color: #007bff;
  color: white;
  padding: 12px 24px; /* 调整提交按钮的内边距 */
  border: none;
  border-radius: 6px;
  font-size: 16px; /* 调整提交按钮字体大小 */
  cursor: pointer;
  transition: background-color 0.3s ease;
  margin-top: 16px; /* 调整提交按钮与上方元素的间距 */
}

.submit-button:hover {
  background-color: #0056b3;
}

.submit-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

/* 返回按钮样式 */
.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  padding: 10px 20px; /* 调整返回按钮的内边距 */
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px; /* 调整返回按钮字体大小 */
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.back-button:hover {
  background-color: #5a6268;
}
</style>